
package RepositoryHarvester;

import java.sql.*;

/**
 *
 * @author Lawrence
 */
public class DatabaseConnection {

    /** The config object for the currently harvesting repository */
	private HarvestConfiguration configuration;
    /** The sql Statment we use to execute queries and updates */
	private Statement stm;
    /** The connection to the sql database. Used to create the Statement */
	private Connection conn;
    /** contains whether the class is currenly connected to the database */
	private boolean connected;

        public static DatabaseConnection instance;
    /**
     * Sets up the local variables and instantiates the class.
     * @param config the configuration object for the currently harvesting repository
     */
	public DatabaseConnection (HarvestConfiguration config)
	{
		connected = false;
		configuration = config;
                instance = this;
	}

        /**
     * Attempts to connect to the specified database.
     * <p>
     * Database user settings and login info is stored in the Configuration.xml file
     * and is read in during the startup phase of the harvster. It is stored
     * in the <code>HarvestConfiguration</code> object
     * @return whether the class was successfull in connecting to the database
     */
	public boolean Connect(){
		connected = true;
		try {
			Class.forName("com.mysql.jdbc.Driver"); // use the jdbc driver
			conn = DriverManager.getConnection (configuration.getDatabaseURL(), configuration.getDatabaseUser(), configuration.getDatabasePassword()); // get a connection
			stm = conn.createStatement(); // create a statement
			if(stm == null)//if there are no errors, yet the statement was not created - normally incorrect authentification
			{
				connected = false;
				System.out.println("Error: Could not connect to database. Incorrect Authentication Details?");
			}
		} catch (Exception e){
			connected = false;
			System.out.println("Error connecting to database: "+e);
		}
		return connected;
	}

        public boolean isConnected()
            {return connected;}

        public void Disconnect()
        {
            try
            {
                if(stm != null)
                {
                    stm.close();
                }
                if(conn != null)
                {
                    conn.close();
                    conn = null;
                }
            }
            catch (SQLException e)
            {
                System.err.println("Failed to disconnect from database");
            }
        }


         /**
     * Given a <code>Record</code> object, this method will add the said
     * record to the batch, which will then later be executed to add it to the
     * database.
     *
     * @param aRecord the record to be stored in the database
     */
	public void addToBatch(Record aRecord){

		try { // try add the query
                        
			String query = "INSERT INTO Archive VALUES('" +aRecord.ID +
                                "', '" + aRecord.institution + "', '" + aRecord.date+
                                "', '" + aRecord.subjects + "')";
			stm.addBatch(query);
			//System.out.println("Added: " + aRecord.getXml());

		} catch (Exception e){
			System.out.println(e);
			// do nothing, exceptions will be thrown for duplicates
		}
	}

        /**
         *  Executes all the requests that have been added to the batch
         */
        public void executeBatch()
        {
            try{
                stm.executeBatch();
            }catch(Exception e){
                System.err.println("Error occured while storing batch: \n"+e);
            }
        }

        public ResultSet doQuery(String query)
        {
            try
            {
                ResultSet results = stm.executeQuery(query);
                return results;
            }
            catch (SQLException e)
            {
                System.err.println("Error occurred while executing query:\n" + e);
                return null;
            }
        }

}
